package democache;

import democache.computer.Computable;
import democache.computer.ExpensiveFunction;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @author Brook
 * 在使用future的情况下产生的重复计算问题，使用putIfAbsent解决
 */
public class DemoCache7<A, V> implements Computable<A, V> {

    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public DemoCache7(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws Exception {
        Future<V> f = cache.get(arg);
        if (f == null) {
            Callable<V> callable = new Callable<V>() {
                @Override
                public V call() throws Exception {
                    return c.compute(arg);
                }
            };
            FutureTask<V> ft = new FutureTask<>(callable);

            f =cache.putIfAbsent(arg,ft);
            if(f == null){
                f = ft;
                System.out.println("从FutrureTasl调用了计算函数");
                ft.run();
            }
        }
        return f.get();
    }

    public static void main(String[] args) throws Exception {
        DemoCache7<String, Integer> demoCache2 = new DemoCache7(new ExpensiveFunction());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果："+result);
            }
        }).start();



        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第三次计算结果："+result);
            }
        }).start();
    }
}
